package com.share.example.stock.service.impl;

import com.alibaba.fastjson.JSON;
import com.share.common.utils.DateUtil;
import com.share.common.utils.DingDingUtil;
import com.share.example.stock.enums.StrategyEnum;
import com.share.example.stock.model.db.StockBaseInfo;
import com.share.example.stock.model.vo.CodePirceO;
import com.share.example.stock.model.vo.MsgVo;
import com.share.example.stock.service.IStockBaseInfoService;
import com.share.example.stock.service.IUserService;
import com.share.example.stock.service.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SendMessageImpl implements SendMessage {
    @Value("${spring.mail.username}")
    private String senderEmail;

    @Resource
    private JavaMailSender javaMailSender;

    @Autowired
    private IUserService userService;

    @Autowired
    private IStockBaseInfoService iStockBaseInfoService;

    @Override
    public int sendMSg2DingDingOrEmail(StrategyEnum strategy, List<CodePirceO> msgList) {
        String title = strategy.getName();
        if (CollectionUtils.isEmpty(msgList)) {
            return 0;
        }

        //1.转换处理
        List<MsgVo> tmpList = new LinkedList<>();
        for (CodePirceO item : msgList) {
            MsgVo vo = new MsgVo();
            vo.setCode(item.getCode());
            vo.setPrice(item.getPrice());
            vo.setOther(item.getOther());
            StockBaseInfo stockInfo = iStockBaseInfoService.getStockCodeMap(item.getCode());
            if (stockInfo != null) {
                vo.setName(stockInfo.getName());
                vo.setIndustryName(stockInfo.getIndustryName());
            }
            tmpList.add(vo);
        }

        //2.排序处理
        List<MsgVo> sortList = tmpList.stream().sorted( //先安装IndustryName 升序
                Comparator.comparing(MsgVo::getIndustryName, Comparator.nullsLast(String::compareTo))
                        .thenComparing(MsgVo::getOther, Comparator.nullsLast(Double::compareTo)).reversed()  //再按照getCoO降序
        ).collect(Collectors.toList());

        //3.发送给dingding
        int i = sendDingDing(title, sortList);

        //4.发送给email
        List<String> emailList = userService.listEmailByStrategy(strategy.getCode());
        sendEmail(title, sortList, emailList);
        return i;
    }

    //发送消息给email
    private int sendEmail(String title, List<MsgVo> msgList, List<String> emailList) {
        if (CollectionUtils.isEmpty(emailList)) {
            return 0;
        }

        if (CollectionUtils.isEmpty(msgList)) {
            return 0;
        }
        String emailContent = getEmailContent(title, msgList);
        String[] emailArr = emailList.toArray(new String[emailList.size()]);
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(senderEmail);
            helper.setTo(emailArr);
            helper.setSubject(title);
            helper.setText(emailContent, true);
            javaMailSender.send(mimeMessage);
            log.info("邮件成功,邮件信息:title={},emailList={},emailContent={}", title, JSON.toJSONString(emailList), emailContent);
        } catch (Exception e) {
            log.error("邮件发送失败title={},emailList={},emailContent={}", title, JSON.toJSONString(emailList), emailContent, e);
            return 0;
        }
        return 1;
    }

    /**
     * <!DOCTYPE html>
     * <html lang="en">
     * <head>
     * <meta charset="UTF-8">
     * <title>aaa</title>
     * </head>
     * <body>
     * <table>
     *     <tr>
     *         <th>code</th>
     *         <th>名称</th>
     *         <th>价格</th>
     *         <th>行业</th>
     *     </tr>
     *     <tr>
     *         <td>January</td>
     *         <td>January</td>
     *         <td>January</td>
     *         <td>$100</td>
     *     </tr>
     * </table>
     * </body>
     * </html>
     *
     * @return
     */
    private String getEmailContent(String title, List<MsgVo> msgList) {
        String str = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>#title#</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "<table>\n" +
                "    <tr>\n" +
                "        <th>#th0#</th>\n" +
                "        <th>#th1#</th>\n" +
                "        <th>#th2#</th>\n" +
                "        <th>#th3#</th>\n" +
                "    </tr>\n" +
                "         #tr-td# \n" +
                "</table>\n" +
                "</body>\n" +
                "</html>";

        str = str.replaceAll("#title#", title);
        str = str.replaceAll("#th0#", "code");
        str = str.replaceAll("#th1#", "名字");
        str = str.replaceAll("#th2#", "价格");
        str = str.replaceAll("#th3#", "行业");
        str = str.replaceAll("#th4#", "其他");

        StringBuffer sb = new StringBuffer();
        for (MsgVo item : msgList) {
            sb.append("<tr>").append(System.lineSeparator());
            sb.append("<td> <a href=\"http://gushitong.baidu.com/stock/ab-#code#\">#code#</a></td>".replaceAll("#code#", item.getCode())).append(System.lineSeparator());
            sb.append("<td>" + item.getName() + "</td>").append(System.lineSeparator());
            sb.append("<td>" + item.getPrice() + "</td>").append(System.lineSeparator());
            sb.append("<td>" + item.getIndustryName() + "</td>").append(System.lineSeparator());
            sb.append("<td>" + item.getOther() + "</td>").append(System.lineSeparator());
            sb.append("</tr>").append(System.lineSeparator());
        }
        str = str.replaceAll("#tr-td#", sb.toString());
        return str;
    }


    //发送给钉钉
    private int sendDingDing(String title, List<MsgVo> msgList) {
        if (CollectionUtils.isEmpty(msgList)) {
            return 0;
        }

        /**
         * | code | name | open | coDo| industry |
         * | :-----| :----- | :---- | :---- | :---- |
         * | 300047 | 迪克 | 7.7 | 0.23| 笔记 |
         */
        StringBuffer sb = new StringBuffer();
        sb.append(title).append("   " + DateUtil.getDateTime()).append(System.lineSeparator());
        sb.append("| code | name | price | industry | other|").append(System.lineSeparator());
        sb.append("| :-----| :----- | :---- | :---- | :---- |").append(System.lineSeparator());
        for (MsgVo item : msgList) {
            StockBaseInfo stockInfo = iStockBaseInfoService.getStockCodeMap(item.getCode());
            if (stockInfo != null) {
                item.setName(stockInfo.getName());
                item.setIndustryName(stockInfo.getIndustryName());
            }
            sb.append("| <a href=\"http://gushitong.baidu.com/stock/ab-#code#\">#code#</a>".replaceAll("#code#", item.getCode()));
            sb.append(" | " + item.getName());
            sb.append(" | " + item.getPrice());
            sb.append(" | " + item.getIndustryName());
            sb.append(" | " + item.getOther() + " |").append(System.lineSeparator());
        }

        String content = sb.toString();
        int i = DingDingUtil.sendMdMsg(title, content);
        if (i > 0) {
            log.info("钉钉消息--发送成功：title={},content={}", title, content);
        } else {
            log.info("钉钉消息--发送异常：title={},content={}", title, content);
        }
        return 1;
    }

    public static void main(String[] args) {
        String sss = "| code | name | open | coDo| industry |\n" +
                "| :-----| :----- | :---- | :---- | :---- |  \n" +
                "| 000926 | 福星股份 | 4.81 | 0.1123 | null |";
        DingDingUtil.sendMdMsg("main", sss);
    }
}
